import queue
import time

from PyQt6.QtWidgets import *
from PyQt6.QtCore import *
from PyQt6.QtGui import *
import traceback


class PigeonBreeder(QThread):
    """
    This class is a loop event of queue.Queue().get_nowait(), all sub threads should send the ui interaction request
     by queue.Queue().put() method, it looks like to release a carrier pigeon, PigeonBreeder is responsible for
     receiving carrier pigeons.
    """
    order = pyqtSignal(tuple)  # (target_ui_widget, operation_method, payload)

    def __init__(self, ui, dispatcher):
        super(PigeonBreeder, self).__init__()
        self.ui, self.dispatcher = ui, dispatcher

    def run(self):
        while 1:
            time.sleep(0.01)
            # msg format sent by sub thread should be tuple with 3 elements, (target_ui_widget, operation, payload)
            try:
                msg = self.dispatcher.get_nowait()
                if len(msg) > 0:
                    self.order.emit(msg)
            except queue.Empty:
                continue
            except Exception as E:
                self.order.emit((self.ui.log_printer, 'QTextBrowser.append', str(E)))
                self.order.emit((self.ui.log_printer, 'QTextBrowser.append', traceback.format_exc()))